package com.yuanfeng.goods.util.es;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yuanfeng.commoms.dto.goods.ShopListQueryDTO;
import com.yuanfeng.commoms.dto.goods.WebGoodsListQueryDTO;
import com.yuanfeng.commoms.dto.shop.ArticleDTO;
import com.yuanfeng.commoms.dto.shop.ArticleShopDTO;
import com.yuanfeng.commoms.dto.shop.WebShopListQueryDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.goods.dto.es.ESCodeEnume;
import com.yuanfeng.goods.mapper.GoodsCommonAttributeAssociationMapper;
import com.yuanfeng.goods.service.ElasticSearchService;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.bulk.*;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * es工具类
 */
@Component
@RefreshScope
public class ESUtils {
    public static final Logger logger = LoggerFactory.getLogger(ESUtils.class);
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static RestHighLevelClient client;
    //批量操作的对象
    private static final BulkProcessor bulkProcessor;
    @Autowired
    private GoodsCommonAttributeAssociationMapper goodsCommonAttributeAssociationMapper;

    private  static GoodsCommonAttributeAssociationMapper esGoodsCommonAttributeAssociationMapper;
    /**
     * @PostContruct是spring框架的注解 spring容器初始化的时候执行该方法
     */
    @PostConstruct
    public void init() {
        client = this.restHighLevelClient;
        this.esGoodsCommonAttributeAssociationMapper = this.goodsCommonAttributeAssociationMapper;

    }
    static {
        bulkProcessor = createBulkProcessor();
    }


    @Value("${es.index}")
    private  String esindex ;
    @Value("${es.index2}")
    private  String esindex2 ;
    @Value("${es.type}")
    private  String estype ;


    private static String index;
    private static String index2;
    private static String type;

    @PostConstruct
    public String getIndex() {
        return index = this.esindex;
    }
    @PostConstruct
    public String getIndex2() {
        return index2 = this.esindex2 ;
    }
    @PostConstruct
    public String getType() {
        return type = this.estype;
    }

    private static ElasticSearchService elasticSearchService;

    @Autowired
    public void setElasticSearchService(ElasticSearchService elasticSearchService) {
        ESUtils.elasticSearchService = elasticSearchService;
    }

    /**
     * 创建商品索引库
     * @throws Exception
     */
    public static ResponseResult setMappings(){
        try {
            //使用client对象创建一个索引库
            //参数1：创建索引请求对象 参数2：请求配置对象
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);

            //创建一个Mappings信息
            XContentBuilder builder = XContentFactory.jsonBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("commonId")//商品id
                    .field("type", "integer")
                    .field("store", true)
                    .endObject()
                    .startObject("goodsId")//货品id
                    .field("type", "integer")
                    .field("store", true)
                    .endObject()
                    .startObject("commonName")//商品名称
                    .field("type", "text")
                    .field("store", true)
                    .startObject("fields")
                    .startObject("raw")//精准匹配字段
                    .field("type", "keyword")
                    .endObject()
                    .startObject("chinese")//分词匹配字段
                    .field("type", "text")
//                    .field("analyzer", "ik_max_word")
//                    .field("search_analyzer", "ik_smart")
                    .endObject()
                    .endObject()
                    .endObject()

                    .startObject("brandName")//品牌名称
                    .field("type", "text")
                    .field("store", true)
                    .field("analyzer", "ik_max_word")
                    .endObject()
                    .startObject("brandId")//品牌id
                    .field("type", "text")
                    .field("store", true)
                    .field("analyzer", "ik_max_word")
                    .endObject()

                    .startObject("attributeContentId")//商品属性内容
                    .field("type", "text")
                    .field("store", true)
                    .field("analyzer", "ik_max_word")
                    .endObject()

                    .startObject("catId")//商品分类id
                    .field("type", "text")
                    .field("store", true)
                    .endObject()

                    .startObject("commonPrice")//商品价格
                    .field("type", "double")
                    .field("store", true)
                    .endObject()
                    .startObject("commonEvaluate")//商品评论数
                    .field("type", "integer")
                    .field("store", true)
                    .endObject()
                    .startObject("commonCollect")//商品收藏量
                    .field("type", "integer")
                    .field("store", true)
                    .endObject()
                    .startObject("commonSalenum")//商品销量
                    .field("type", "integer")
                    .field("store", true)
                    .endObject()
                    .startObject("shopSelfSupport")//是否自营商品 1 不是 2 是
                    .field("type", "integer")
                    .field("store", true)
                    .endObject()
                    .startObject("updateTime")//更新时间
                    .field("type", "date")
                    .field("store", true)
                    .field("format", "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis")
                    .endObject()
                    .endObject()
                    .endObject();
            createIndexRequest.mapping(builder);
            //使用client把mapping信息设置到索引库中
            client.indices().create(createIndexRequest, RequestOptions.DEFAULT);

            return ResponseResult.success(ESCodeEnume.INDEX_CREATE_SUCCESS.getCode(), ESCodeEnume.INDEX_CREATE_SUCCESS.getMsg());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(ESCodeEnume.INDEX_CREATE_FAIL.getCode(), ESCodeEnume.INDEX_CREATE_FAIL.getMsg());
    }
    public static ResponseResult deleteGoodsIndex() {
        boolean acknowledged = false;
        try {
            //创建删除索引请求
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
            //        执行
            AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            //得到相应
            acknowledged = delete.isAcknowledged();
            if(acknowledged){
                return ResponseResult.success(ESCodeEnume.INDEX_DELETE_SUCCESS.getCode(), ESCodeEnume.INDEX_DELETE_SUCCESS.getMsg());
            }else{
                return ResponseResult.success(ESCodeEnume.INDEX_DELETE_FAIL.getCode(), ESCodeEnume.INDEX_DELETE_FAIL.getMsg());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.success(ESCodeEnume.INDEX_DELETE_FAIL.getCode(), ESCodeEnume.INDEX_DELETE_FAIL.getMsg());
    }
    //批量导入商品
    public static ResponseResult importData(List<ArticleDTO> articleDTOS){
        try {
            //先判断索引库是否存在 不存在 就创建
            GetIndexRequest request = new GetIndexRequest();
            boolean exists = client.indices().exists(request.indices(index), RequestOptions.DEFAULT);
            if(exists) {
                System.out.println("商品索引库存在");
            }else{
                System.out.println("商品索引库不存在");
                ResponseResult resp = setMappings();
                System.out.println(resp.getMessage());
            }
            List<Integer> commonIds = new ArrayList<>();
            List<IndexRequest> indexRequests = new ArrayList<>();
            if(null != articleDTOS && !articleDTOS.isEmpty()){
                articleDTOS.forEach(e -> {
                    IndexRequest request1 = new IndexRequest(index);
                    //填充id
                    request1.id(e.getCommonId().toString());
                    commonIds.add(e.getCommonId());
                    //先不修改id
                    request1.source(JSON.toJSONString(e), XContentType.JSON);
                    request1.opType(DocWriteRequest.OpType.CREATE);
                    System.out.println(e.getCommonName()+"导入");
                    indexRequests.add(request1);
                });
                //先删除后插入
                delete(commonIds);
                indexRequests.forEach(bulkProcessor::add);
            }
            return ResponseResult.success(1,"数据导入成功");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(1,"数据导入失败");
    }
    /*
     * 删除所有商品
     * */
    public static ResponseResult deleteAll(){
        try {
            //1.创建 SearchRequest搜索请求
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(index);//指定要查询的索引
            //2.创建 SearchSourceBuilder条件构造。
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
            searchSourceBuilder.query(matchAllQueryBuilder);
            //设置分页
            searchSourceBuilder.from(0);
            searchSourceBuilder.size(1000);
            //3.将 SearchSourceBuilder 添加到 SearchRequest中
            searchRequest.source(searchSourceBuilder);
            //4.执行查询
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = searchResponse.getHits();
            for (SearchHit hit : hits) {
                Map<String, Object> map = hit.getSourceAsMap();
                DeleteRequest deleteRequest=new DeleteRequest();
                deleteRequest.index(index);
                deleteRequest.id(map.get("commonId").toString());
                client.delete(deleteRequest,RequestOptions.DEFAULT);
                System.out.println("文档"+map.get("commonId")+"已删除");
            }
            long total = hits.getTotalHits().value;
            if(0 == Long.valueOf(total)){
                return ResponseResult.success(ESCodeEnume.DATA_DELETE_SUCCESS.getCode(), ESCodeEnume.DATA_DELETE_SUCCESS.getMsg());
            }else{
                deleteAll();
            }
            return ResponseResult.success(ESCodeEnume.DATA_DELETE_SUCCESS.getCode(), ESCodeEnume.DATA_DELETE_SUCCESS.getMsg());
        } catch (ElasticsearchParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
    /**
     * 批量  添加 / 修改 商品
     */
    public static ResponseResult addOrUpdate(List<ArticleDTO> list){
        try {
            if(!list.isEmpty()){
                //数据导入
                importData(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(ESCodeEnume.INPUT_SUCCESS.getCode(), ESCodeEnume.INPUT_SUCCESS.getMsg());
    }
    /**
     * 批量  添加 / 修改 店铺
     */
    public static ResponseResult addOrUpdateShop(List<ArticleShopDTO> list){
        try {
            if(list.size()>0){
                importShopData(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(ESCodeEnume.INPUT_SUCCESS.getCode(), ESCodeEnume.INPUT_SUCCESS.getMsg());
    }
    /**
     * 批量 删除 商品
     */
    public static ResponseResult delete(List<Integer> list){
        try {
            if(list.size()>0){
                for (Object goodsId : list) {
                    DeleteRequest deleteRequest=new DeleteRequest();
                    deleteRequest.index(index);
                    deleteRequest.id(goodsId.toString());
                    client.delete(deleteRequest,RequestOptions.DEFAULT);
                    System.out.println("文档"+goodsId+"已删除");
                    //删除商品缓存
                    RedisUtil.remove("yuanfeng_pc_goods_commonId_"+goodsId);
                    RedisUtil.remove("yuanfeng_h5_goods_commonId_"+goodsId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(ESCodeEnume.DELETE_SUCCESS.getCode(), ESCodeEnume.DELETE_SUCCESS.getMsg());
    }
    /**
     * 批量 删除 店铺
     */
    public static ResponseResult deleteShop(List<Integer> list){
        try {
            if(list.size()>0){
                for (Integer shopId : list) {
                    DeleteRequest deleteRequest=new DeleteRequest();
                    deleteRequest.index(index2);
                    deleteRequest.id(shopId.toString());
                    client.delete(deleteRequest,RequestOptions.DEFAULT);
                    System.out.println("文档"+shopId+"已删除");
                    //删除店铺缓存
                    RedisUtil.remove("yuanfeng_pc_shop_shopId_"+shopId);
                    RedisUtil.remove("yuanfeng_h5_shop_shopId_"+shopId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(ESCodeEnume.DELETE_SUCCESS.getCode(), ESCodeEnume.DELETE_SUCCESS.getMsg());
    }
    /**
     * pc 高亮显示查询结果 商品
     *
     * @throws Exception
     */
    public static Map<String, Object> pcSeachGoodsData(WebGoodsListQueryDTO webGoodsListQueryParam) throws Exception {
        //返回值
        Map<String, Object> map = new HashMap<>();
        try {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(index);//指定要查询的索引

            HighlightBuilder highlightBuilder = new HighlightBuilder(); //创建高亮对象
            String highlightFiled = "commonName.chinese";//指定查的字段
           //多条件查询
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();// 从某个字段中查询出某个值
            String commonName = webGoodsListQueryParam.getCommonName();

            //编号匹配
            MatchQueryBuilder codeMatchQueryBuilder = QueryBuilders.matchQuery("commonName.chinese", commonName);
            MatchQueryBuilder codeRawMatchQueryBuilder = QueryBuilders.matchQuery("commonName.raw", commonName);
            codeRawMatchQueryBuilder.boost(10f);
            boolQueryBuilder.must(codeMatchQueryBuilder).should(codeRawMatchQueryBuilder);
            //根据品牌查询
            if(null != webGoodsListQueryParam.getBrandIdList() && !webGoodsListQueryParam.getBrandIdList().isEmpty()){
                boolQueryBuilder.must(QueryBuilders.termsQuery("brandId",webGoodsListQueryParam.getBrandIdList()));//精确匹配
            }
            //根据商品属性查询
            if(null != webGoodsListQueryParam.getAttributeContentIdList() && !webGoodsListQueryParam.getAttributeContentIdList().isEmpty()){
                List<String> contentIdPram = new ArrayList<>();
                for (String s : webGoodsListQueryParam.getAttributeContentIdList()) {
                    contentIdPram.add("-" + s + "-");
                }
                boolQueryBuilder.must(QueryBuilders.matchQuery("attributeContentId",contentIdPram));//模糊匹配
            }
            // 设置查询条件
            searchSourceBuilder.query(boolQueryBuilder);
            if (null == webGoodsListQueryParam.getOrderType() || 3 == webGoodsListQueryParam.getOrderType()) { //综合查询  取消排序 因为es默认排序是按搜索内容的匹配度排序的，加了排序会打乱es默认排序，在精确搜索时搜索的内容不会展示在最上面
                // 设置按照匹配度评分排序
                searchSourceBuilder.sort("_score");
            } else if (5 == webGoodsListQueryParam.getOrderType()) {//根据评论查询
                if (null != webGoodsListQueryParam.getCommentOrder() && 0 != webGoodsListQueryParam.getCommentOrder()) {// 评论排序 1降序，2升序 0 不生效
                    if (1 == webGoodsListQueryParam.getCommentOrder()) {
                        searchSourceBuilder.sort("commonEvaluate", SortOrder.DESC);
                    } else {
                        searchSourceBuilder.sort("commonEvaluate", SortOrder.ASC);
                    }
                }
                searchSourceBuilder.sort("updateTime", SortOrder.DESC);
            } else if (1 == webGoodsListQueryParam.getOrderType()) {//根据价格查询
                if (null != webGoodsListQueryParam.getPriceOrder() && 0 != webGoodsListQueryParam.getPriceOrder()) { // 价格排序 1降序，2升序 0 不生效
                    if (1 == webGoodsListQueryParam.getPriceOrder()) {
                        searchSourceBuilder.sort("commonPrice", SortOrder.DESC);
                    } else {
                        searchSourceBuilder.sort("commonPrice", SortOrder.ASC);
                    }
                }
                searchSourceBuilder.sort("updateTime", SortOrder.DESC);
            }
            //设置高亮显示的字段
            highlightBuilder.field(highlightFiled); //为高亮设置字段
            //多个字段高亮显示，要设置为false
            highlightBuilder.requireFieldMatch(true);
            //设置高亮显示的前缀
            highlightBuilder.preTags("<font style=\"color:red;\">");//设置高亮前标签
            //设置高亮显示的后缀
            highlightBuilder.postTags("</font>");//设置高亮后标签
            //最大高亮分片数
            highlightBuilder.fragmentSize(800000);
            //从第一片片获取获取高亮片段
            highlightBuilder.numOfFragments(0);
            //执行查询
            searchSourceBuilder.highlighter(highlightBuilder);
//            searchRequest.source(searchSourceBuilder);
            //设置分页
            searchSourceBuilder.from((webGoodsListQueryParam.getPage() - 1) * webGoodsListQueryParam.getLimit());
            searchSourceBuilder.size(webGoodsListQueryParam.getLimit());
            //3.将 SearchSourceBuilder 添加到 SearchRequest中
            searchRequest.source(searchSourceBuilder);
            //4.执行查询
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            //取插叙结果
            SearchHits hits = searchResponse.getHits();
            //取查询结果的总记录数
            System.out.println("查询结果总记录条数:   " + hits.getTotalHits().value);
            ArrayList<ArticleDTO> list = new ArrayList<>();
            //查询结果列表
            Iterator<SearchHit> iterator = hits.iterator();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while (iterator.hasNext()) {
                SearchHit searchHit = iterator.next();
                //打印文档对象，以json格式输出
                System.out.println(searchHit.getSourceAsString());
                //取文档的属性
                Map<String, Object> source = searchHit.getSourceAsMap();
                Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
                //取title高亮显示的结果
                HighlightField field = highlightFields.get(highlightFiled);
                Text[] fragments = field.getFragments();
                ArticleDTO articleDto = new ArticleDTO();
                articleDto.setCommonId((Integer) source.get("commonId"));
                articleDto.setGoodsId((Integer) source.get("goodsId"));
                articleDto.setCommonName((String) source.get("commonName"));
                articleDto.setCommonPrice((Double) source.get("commonPrice"));
                articleDto.setCommonEvaluate((Integer) source.get("commonEvaluate"));
                articleDto.setCommonSalenum((Integer) source.get("commonSalenum"));
                articleDto.setCommonCollect((Integer) source.get("commonCollect"));
                articleDto.setShopSelfSupport((Integer) source.get("shopSelfSupport"));

                if (fragments != null) {
                    String fragment = fragments[0].toString();
                    articleDto.setCommonName(fragment);
                }
                list.add(articleDto);
            }

            map.put("list", list);
            map.put("count", hits.getTotalHits().value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
    /**
     * pc 高亮显示查询结果 商铺
     * @throws Exception
     */
    public static Map<String,Object>  pcSeachShopData(WebShopListQueryDTO webGoodsListQueryParam) throws Exception {
        //返回值
        Map<String,Object> map = new HashMap<>();
        try {
            //1.创建 SearchRequest搜索请求
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(index2);//指定要查询的索引

            HighlightBuilder highlightBuilder=new HighlightBuilder(); //创建高亮对象
            String highlightFiled = "shopName.chinese";//指定查的字段
            //多条件查询
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();// 从某个字段中查询出某个值
            String shopName = webGoodsListQueryParam.getShopName();

            //编号匹配
            MatchQueryBuilder codeMatchQueryBuilder = QueryBuilders.matchQuery("shopName.chinese", shopName);
            MatchQueryBuilder codeRawMatchQueryBuilder = QueryBuilders.matchQuery("shopName.raw", shopName);
            codeRawMatchQueryBuilder.boost(10f);
            queryBuilder.must(codeMatchQueryBuilder).should(codeRawMatchQueryBuilder);
            if(null != webGoodsListQueryParam.getOrderType() && 1 != webGoodsListQueryParam.getOrderType()){
                if(null != webGoodsListQueryParam.getDistrictId()){//根据区域id查询
                    queryBuilder.must(QueryBuilders.queryStringQuery(webGoodsListQueryParam.getDistrictId().toString()).defaultField("districtId"));
                }
                if(2 == webGoodsListQueryParam.getOrderType()){//根据收藏量排序
                    searchSourceBuilder.sort("shopCollect", SortOrder.ASC);
                }
            }
            if(null != webGoodsListQueryParam.getShopSelfSupport() && "" != webGoodsListQueryParam.getShopSelfSupport()){//是否自营店铺 1 不是 2 是
                queryBuilder.must(QueryBuilders.queryStringQuery(webGoodsListQueryParam.getShopSelfSupport()).defaultField("shopSelfSupport"));
            }
            searchSourceBuilder.query(queryBuilder);
            searchSourceBuilder.sort("shopOperatorTime", SortOrder.DESC);
            //设置高亮显示的字段
            highlightBuilder.field(highlightFiled); //为高亮设置字段
            //多个字段高亮显示，要设置为false
            highlightBuilder.requireFieldMatch(true);
            //设置高亮显示的前缀
            highlightBuilder.preTags("<font style=\"color:red;\">");//设置高亮前标签
            //设置高亮显示的后缀
            highlightBuilder.postTags("</font>");//设置高亮后标签
            //最大高亮分片数
            highlightBuilder.fragmentSize(800000);
            //从第一片片获取获取高亮片段
            highlightBuilder.numOfFragments(0);
            //执行查询
            searchSourceBuilder.highlighter(highlightBuilder);
            //设置分页
            searchSourceBuilder.from((webGoodsListQueryParam.getPage() - 1) * webGoodsListQueryParam.getLimit());
            searchSourceBuilder.size(webGoodsListQueryParam.getLimit());
            //3.将 SearchSourceBuilder 添加到 SearchRequest中
            searchRequest.source(searchSourceBuilder);
            //4.执行查询
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            //取插叙结果
            SearchHits hits = searchResponse.getHits();
            //取查询结果的总记录数
            System.out.println("查询结果总记录条数" + hits.getTotalHits().value);
            ArrayList<ArticleShopDTO> list = new ArrayList<>();
            //查询结果列表
            Iterator<SearchHit> iterator = hits.iterator();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while (iterator.hasNext()) {
                SearchHit searchHit = iterator.next();
                //打印文档对象，以json格式输出
                System.out.println(searchHit.getSourceAsString());
                //取文档的属性
                Map<String, Object> source = searchHit.getSourceAsMap();
                Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
                //取title高亮显示的结果
                HighlightField field = highlightFields.get(highlightFiled);
                Text[] fragments = field.getFragments();
                ArticleShopDTO articleShopDto = new ArticleShopDTO();
                articleShopDto.setShopId((Integer) source.get("shopId"));
                articleShopDto.setShopName((String) source.get("shopName"));
                articleShopDto.setShopCollect((Integer) source.get("shopCollect"));
                articleShopDto.setDistrictId((Integer) source.get("districtId"));
                articleShopDto.setShopSelfSupport((Boolean) source.get("shopSelfSupport"));
//                articleShopDto.setShopOperatorTime(formatter.parse((String) source.get("shopOperatorTime")));

                if(fragments!=null){
                    String fragment=fragments[0].toString();
                    articleShopDto.setShopName(fragment);
                }
                list.add(articleShopDto);
            }
            map.put("list",list);
            map.put("count",hits.getTotalHits().value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * h5 高亮显示查询结果 商品
     * @throws Exception
     */
    public static Map<String,Object>  h5SeachGoodsData(WebGoodsListQueryDTO webGoodsListQueryParam) throws Exception {
        //返回值
        Map<String,Object> map = new HashMap<>();
        //1.创建 SearchRequest搜索请求
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(index);//指定要查询的索引

        HighlightBuilder highlightBuilder=new HighlightBuilder(); //创建高亮对象
        String highlightFiled = "commonName.chinese";//指定查的字段
        webGoodsListQueryParam.setPage((webGoodsListQueryParam.getPage() - 1) * webGoodsListQueryParam.getLimit());//设置分页
        //多条件查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();// 从某个字段中查询出某个值
        String commonName = webGoodsListQueryParam.getCommonName();

        //按照商品名称匹配
        //分词匹配
        MatchQueryBuilder nameMatchQueryBuilder = QueryBuilders.matchQuery("commonName.chinese", commonName);
        //精准匹配
        MatchQueryBuilder nameRawMatchQueryBuilder = QueryBuilders.matchQuery("commonName.raw", commonName);
        nameRawMatchQueryBuilder.boost(10f);
        boolQueryBuilder.must(nameMatchQueryBuilder).should(nameRawMatchQueryBuilder);
        //根据品牌查询
        if(null != webGoodsListQueryParam.getBrandIdList() && !webGoodsListQueryParam.getBrandIdList().isEmpty()){
//                boolQueryBuilder.must(QueryBuilders.termQuery("brandId",webGoodsListQueryParam.getBrandName()));//精确匹配
            boolQueryBuilder.must(QueryBuilders.termsQuery("brandId",webGoodsListQueryParam.getBrandIdList()));//精确匹配
        }
        //根据商品属性查询
        if(null != webGoodsListQueryParam.getAttributeContentIdList() && !webGoodsListQueryParam.getAttributeContentIdList().isEmpty()){
            List<String> contentIdPram = new ArrayList<>();
            for (String s : webGoodsListQueryParam.getAttributeContentIdList()) {
                contentIdPram.add("-" + s + "-");
            }
            boolQueryBuilder.must(QueryBuilders.matchQuery("attributeContentId",contentIdPram));//模糊匹配
        }
        // 设置查询条件
        searchSourceBuilder.query(boolQueryBuilder);

        if(null != webGoodsListQueryParam.getMinPrice() && null ==  webGoodsListQueryParam.getMaxPrice()){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("commonPrice").from(webGoodsListQueryParam.getMinPrice().doubleValue()));// 价格区间
        }else if(null == webGoodsListQueryParam.getMinPrice() && null !=  webGoodsListQueryParam.getMaxPrice()){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("commonPrice").to(webGoodsListQueryParam.getMaxPrice().doubleValue()));// 价格区间
        }else if(null != webGoodsListQueryParam.getMinPrice()){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("commonPrice").from(webGoodsListQueryParam.getMinPrice().doubleValue()).to(webGoodsListQueryParam.getMaxPrice().doubleValue()));// 价格区间
        }
        if(null != webGoodsListQueryParam.getShopSelfSupport() && !webGoodsListQueryParam.getShopSelfSupport().isEmpty()){
            if(webGoodsListQueryParam.getShopSelfSupport().equals("true")){
                boolQueryBuilder.must(QueryBuilders.queryStringQuery("0").defaultField("shopSelfSupport"));//是否 自营  1不是 0 是
            }else{
                boolQueryBuilder.must(QueryBuilders.queryStringQuery("1").defaultField("shopSelfSupport"));//是否 自营  1不是 0 是
            }
        }
        searchSourceBuilder.query(boolQueryBuilder);
        if(null == webGoodsListQueryParam.getOrderType() || 3 == webGoodsListQueryParam.getOrderType()){ //综合查询  取消排序 因为es默认排序是按搜索内容的匹配度排序的，加了排序会打乱es默认排序，在精确搜索时搜索的内容不会展示在最上面
            // 设置按照匹配度评分排序
            searchSourceBuilder.sort("_score");
        }else if(5 == webGoodsListQueryParam.getOrderType()) {//评论数查询
            if(null != webGoodsListQueryParam.getCommentOrder() && 0 != webGoodsListQueryParam.getCommentOrder()){// 评论排序 1降序，2升序 0 不生效
                if(1 == webGoodsListQueryParam.getCommentOrder()){
                    searchSourceBuilder.sort("commonEvaluate", SortOrder.DESC);
                }else{
                    searchSourceBuilder.sort("commonEvaluate", SortOrder.ASC);
                }
            }
            searchSourceBuilder.sort("updateTime", SortOrder.DESC);
        }else if(1 == webGoodsListQueryParam.getOrderType()){//根据价格排序
            if(null != webGoodsListQueryParam.getPriceOrder() && 0 != webGoodsListQueryParam.getPriceOrder()){ // 价格排序 1降序，2升序 0 不生效
                if(1 == webGoodsListQueryParam.getPriceOrder()){
                    searchSourceBuilder.sort("commonPrice", SortOrder.DESC);
                }else{
                    searchSourceBuilder.sort("commonPrice", SortOrder.ASC);
                }
            }
            searchSourceBuilder.sort("updateTime", SortOrder.DESC);
        }

        //设置高亮显示的字段
        highlightBuilder.field(highlightFiled); //为高亮设置字段
        //多个字段高亮显示，要设置为false
        highlightBuilder.requireFieldMatch(true);
        //设置高亮显示的前缀
        highlightBuilder.preTags("<font style=\"color:red;\">");//设置高亮前标签
        //设置高亮显示的后缀
        highlightBuilder.postTags("</font>");//设置高亮后标签
        //最大高亮分片数
        highlightBuilder.fragmentSize(800000);
        //从第一片片获取获取高亮片段
        highlightBuilder.numOfFragments(0);
        //执行查询
        searchSourceBuilder.highlighter(highlightBuilder);
        //设置分页
        searchSourceBuilder.from(webGoodsListQueryParam.getPage());
        searchSourceBuilder.size(webGoodsListQueryParam.getLimit());
        //3.将 SearchSourceBuilder 添加到 SearchRequest中
        searchRequest.source(searchSourceBuilder);
        //4.执行查询
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //取插叙结果
        SearchHits hits = searchResponse.getHits();
        //取查询结果的总记录数
        System.out.println(" :查询结果总记录条数:   " + hits.getTotalHits().value);
        ArrayList<ArticleDTO> list = new ArrayList<>();
        //查询结果列表
        Iterator<SearchHit> iterator = hits.iterator();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next();
            //打印文档对象，以json格式输出
            System.out.println(searchHit.getSourceAsString());
            //取文档的属性
            Map<String, Object> source = searchHit.getSourceAsMap();
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            //取title高亮显示的结果
            HighlightField field = highlightFields.get(highlightFiled);
            Text[] fragments = field.getFragments();
            ArticleDTO articleDto = new ArticleDTO();
            articleDto.setCommonId((Integer) source.get("commonId"));
            articleDto.setGoodsId((Integer) source.get("goodsId"));
            articleDto.setCommonName((String) source.get("commonName"));
            articleDto.setCommonPrice((Double) source.get("commonPrice"));
            articleDto.setCommonEvaluate((Integer) source.get("commonEvaluate"));
            articleDto.setCommonSalenum((Integer) source.get("commonSalenum"));
            articleDto.setCommonCollect((Integer) source.get("commonCollect"));
            articleDto.setShopSelfSupport((Integer) source.get("shopSelfSupport"));
            articleDto.setUpdateTime(new Date((Long) source.get("updateTime")));

            if(fragments!=null){
                String fragment=fragments[0].toString();
                articleDto.setCommonName(fragment);
            }
            list.add(articleDto);
        }
        map.put("list",list);
        map.put("count",hits.getTotalHits().value);
        return map;
    }

    /**
     * h5 高亮显示查询结果  商铺
     * @throws Exception
     */
    public static Map<String,Object>  h5SeachShopData(ShopListQueryDTO shopListQueryParam) throws Exception {
        //返回值
        Map<String,Object> map = new HashMap<>();
        //1.创建 SearchRequest搜索请求
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(index2);//指定要查询的索引

        HighlightBuilder highlightBuilder=new HighlightBuilder(); //创建高亮对象
        String highlightFiled = "shopName.chinese";//指定查的字段
        shopListQueryParam.setPage((shopListQueryParam.getPage() - 1) * shopListQueryParam.getLimit());//设置分页
        //多条件查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();// 从某个字段中查询出某个值
        String shopName = shopListQueryParam.getShopName();
//            queryBuilder.must(QueryBuilders.queryStringQuery(shopName).defaultField("shopName"));//根据商品名称查询
        //编号匹配
        MatchQueryBuilder codeMatchQueryBuilder = QueryBuilders.matchQuery("shopName.chinese", shopName);
        MatchQueryBuilder codeRawMatchQueryBuilder = QueryBuilders.matchQuery("shopName.raw", shopName);
        codeRawMatchQueryBuilder.boost(10f);
        queryBuilder.must(codeMatchQueryBuilder).should(codeRawMatchQueryBuilder);
        // 设置查询条件
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.sort("shopOperatorTime", SortOrder.DESC);
        //设置高亮显示的字段
        highlightBuilder.field(highlightFiled); //为高亮设置字段
        //多个字段高亮显示，要设置为false
        highlightBuilder.requireFieldMatch(true);
        //设置高亮显示的前缀
        highlightBuilder.preTags("<font style=\"color:red;\">");//设置高亮前标签
        //设置高亮显示的后缀
        highlightBuilder.postTags("</font>");//设置高亮后标签
        //最大高亮分片数
        highlightBuilder.fragmentSize(800000);
        //从第一片片获取获取高亮片段
        highlightBuilder.numOfFragments(0);
        //执行查询
        searchSourceBuilder.highlighter(highlightBuilder);
        //设置分页
        searchSourceBuilder.from(shopListQueryParam.getPage());
        searchSourceBuilder.size(shopListQueryParam.getLimit());
        //3.将 SearchSourceBuilder 添加到 SearchRequest中
        searchRequest.source(searchSourceBuilder);
        //4.执行查询
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //取插叙结果
        SearchHits hits = searchResponse.getHits();
        //取查询结果的总记录数
        System.out.println("查询结果总记录条数" + hits.getTotalHits().value);
        ArrayList<ArticleShopDTO> list = new ArrayList<>();
        //查询结果列表
        Iterator<SearchHit> iterator = hits.iterator();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next();
            //打印文档对象，以json格式输出
            System.out.println(searchHit.getSourceAsString());
            //取文档的属性
            Map<String, Object> source = searchHit.getSourceAsMap();
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            //取title高亮显示的结果
            HighlightField field = highlightFields.get(highlightFiled);
            Text[] fragments = field.getFragments();
            ArticleShopDTO articleShopDto = new ArticleShopDTO();
            articleShopDto.setShopId((Integer) source.get("shopId"));
            articleShopDto.setShopName((String) source.get("shopName"));
            articleShopDto.setShopCollect((Integer) source.get("shopCollect"));
            articleShopDto.setDistrictId((Integer) source.get("districtId"));
            articleShopDto.setShopSelfSupport((Boolean) source.get("shopSelfSupport"));
            articleShopDto.setShopOperatorTime(new Date((Long) source.get("shopOperatorTime")));

            if (fragments != null) {
                String fragment = fragments[0].toString();
                articleShopDto.setShopName(fragment);
            }
            list.add(articleShopDto);
        }
        map.put("list", list);
        map.put("count", hits.getTotalHits().value);
        return map;
    }

    /**
     * 创建店铺索引库
     *
     * @throws Exception
     */
    public static ResponseResult setShopMappings() {
        try {
            //使用client对象创建一个索引库
            //参数1：创建索引请求对象 参数2：请求配置对象
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(index2);

            //创建一个Mappings信息
            XContentBuilder builder = XContentFactory.jsonBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("shopId")//店铺id
                    .field("type", "integer")
                    .field("store", true)
                    .endObject()
                    .startObject("shopName")//店铺名称
                    .field("type", "text")
                    .field("store", true)
                    .startObject("fields")
                    .startObject("raw")//精准匹配字段
                    .field("type", "keyword")
                    .endObject()
                    .startObject("chinese")//分词匹配字段
                    .field("type", "text")
//                    .field("analyzer", "ik_max_word")
//                    .field("search_analyzer", "ik_smart")
                    .endObject()
                    .endObject()
                    .endObject()
                    .startObject("shopCollect")//店铺粉丝数
                    .field("type", "integer")
                    .field("store", true)
                    .endObject()
                    .startObject("districtId")//地区id
                    .field("type", "integer")
                    .field("store", true)
                    .endObject()
                    .startObject("shopSelfSupport")//是否自营商品 true 是 false 否
                    .field("type", "boolean")
                    .field("store", true)
                    .endObject()
                    .startObject("shopOperatorTime")//审核时间
                    .field("type", "date")
                    .field("store", true)
                    .field("format", "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis")
                    .endObject()
                    .endObject()
                    .endObject();
            createIndexRequest.mapping(builder);
            //使用client把mapping信息设置到索引库中
			client.indices().create(createIndexRequest, RequestOptions.DEFAULT);

            return ResponseResult.success(ESCodeEnume.INDEX_CREATE_SUCCESS.getCode(), ESCodeEnume.INDEX_CREATE_SUCCESS.getMsg());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(ESCodeEnume.INDEX_CREATE_FAIL.getCode(), ESCodeEnume.INDEX_CREATE_FAIL.getMsg());
    }
    public static ResponseResult deleteShopIndex() {
        boolean acknowledged = false;
        try {
            //创建删除索引请求
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index2);
            //        执行
            AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            //得到相应
            acknowledged = delete.isAcknowledged();
            if(acknowledged){
            	return ResponseResult.success(ESCodeEnume.INDEX_CREATE_SUCCESS.getCode(), ESCodeEnume.INDEX_CREATE_SUCCESS.getMsg());
            }else{
            	return ResponseResult.success(ESCodeEnume.INDEX_CREATE_FAIL.getCode(), ESCodeEnume.INDEX_CREATE_FAIL.getMsg());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.success("删除索引库失败");
    }
    //批量导入店铺
    public static ResponseResult importShopData(List<ArticleShopDTO> articleShopDTOS){
        try {
            //先判断索引库是否存在 不存在 就创建
            GetIndexRequest request = new GetIndexRequest();
            boolean exists = client.indices().exists(request.indices(index2), RequestOptions.DEFAULT);
            if(exists) {
                System.out.println("店铺索引库存在");
            }else{
                System.out.println("店铺索引库不存在");
                ResponseResult resp = setShopMappings();
                System.out.println(resp.getMessage());
            }
            List<Integer> shopIds = new ArrayList<>();
            List<IndexRequest> indexRequests = new ArrayList<>();
            if(null != articleShopDTOS && articleShopDTOS.size() > 0){
                articleShopDTOS.forEach(e -> {
                    IndexRequest request1 = new IndexRequest(index2);
                    //填充id
                    request1.id(e.getShopId().toString());
                    shopIds.add(e.getShopId());
                    //先不修改id
                    request1.source(JSON.toJSONString(e), XContentType.JSON);
                    request1.opType(DocWriteRequest.OpType.CREATE);
                    System.out.println(e.getShopName()+"导入");
                    indexRequests.add(request1);
                });
                //先删除后插入
                deleteShop(shopIds);
                indexRequests.forEach(bulkProcessor::add);
            }
            return ResponseResult.success(ESCodeEnume.INPUT_SUCCESS.getCode(), ESCodeEnume.INPUT_SUCCESS.getMsg());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(ESCodeEnume.INPUT_FAIL.getCode(), ESCodeEnume.INPUT_FAIL.getMsg());
    }
    /*
     * 删除所有店铺
     * */
    public static ResponseResult deleteShopAll(){
        try {
            //1.创建 SearchRequest搜索请求
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(index2);//指定要查询的索引
            //2.创建 SearchSourceBuilder条件构造。
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
            searchSourceBuilder.query(matchAllQueryBuilder);
            //设置分页
            searchSourceBuilder.from(0);
            searchSourceBuilder.size(1000);

            //3.将 SearchSourceBuilder 添加到 SearchRequest中
            searchRequest.source(searchSourceBuilder);
            //4.执行查询
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = searchResponse.getHits();
            for (SearchHit hit : hits) {
                Map<String, Object> map = hit.getSourceAsMap();
                System.out.println(map);
                DeleteRequest deleteRequest=new DeleteRequest();
                deleteRequest.index(index2);
                deleteRequest.id(map.get("shopId").toString());
                client.delete(deleteRequest,RequestOptions.DEFAULT);
                System.out.println("文档"+map.get("shopId")+"已删除");
            }
            long total = hits.getTotalHits().value;
            if(0 == Long.valueOf(total)){
                return ResponseResult.success(ESCodeEnume.DELETE_SUCCESS.getCode(), ESCodeEnume.DELETE_SUCCESS.getMsg());
            }else{
                deleteShopAll();
            }
            return ResponseResult.success(ESCodeEnume.DELETE_SUCCESS.getCode(), ESCodeEnume.DELETE_SUCCESS.getMsg());
        } catch (ElasticsearchParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }

    private static BulkProcessor createBulkProcessor() {

        BulkProcessor.Listener listener = new BulkProcessor.Listener() {
            @Override
            public void beforeBulk(long executionId, BulkRequest request) {
                logger.info("1. 【beforeBulk】批次[{}] 携带 {} 请求数量", executionId, request.numberOfActions());
            }

            @Override
            public void afterBulk(long executionId, BulkRequest request,
                                  BulkResponse response) {
                if (!response.hasFailures()) {
                    logger.info("2. 【afterBulk-成功】批量 [{}] 完成在 {} ms", executionId, response.getTook().getMillis());
                } else {
                    BulkItemResponse[] items = response.getItems();
                    for (BulkItemResponse item : items) {
                        if (item.isFailed()) {
                            logger.info("2. 【afterBulk-失败】批量 [{}] 出现异常的原因 : {}", executionId, item.getFailureMessage());
                            break;
                        }
                    }
                }
            }

            @Override
            public void afterBulk(long executionId, BulkRequest request,
                                  Throwable failure) {

                List<DocWriteRequest<?>> requests = request.requests();
                List<String> esIds = requests.stream().map(DocWriteRequest::id).collect(Collectors.toList());
                logger.error("3. 【afterBulk-failure失败】es执行bluk失败,失败的esId为：{}", esIds, failure);
            }
        };

        BulkProcessor.Builder builder = BulkProcessor.builder(((bulkRequest, bulkResponseActionListener) -> {
            client.bulkAsync(bulkRequest, RequestOptions.DEFAULT, bulkResponseActionListener);
        }), listener);
        //到达10000条时刷新
        builder.setBulkActions(10000);
        //内存到达8M时刷新
        builder.setBulkSize(new ByteSizeValue(8L, ByteSizeUnit.MB));
        //设置的刷新间隔10s
        builder.setFlushInterval(TimeValue.timeValueSeconds(10));
        //设置允许执行的并发请求数。
        builder.setConcurrentRequests(8);
        //设置重试策略
        builder.setBackoffPolicy(BackoffPolicy.constantBackoff(TimeValue.timeValueSeconds(1), 3));
        return builder.build();
    }

    public static Map<String, Object> querySeachBrandAttributeData(WebGoodsListQueryDTO webGoodsListQueryParam) {
        //返回值
        Map<String,Object> map = new HashMap<>();
        try {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(index);//指定要查询的索引

            //多条件查询
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();// 从某个字段中查询出某个值
            String commonName = webGoodsListQueryParam.getCommonName();
            //编号匹配
            MatchQueryBuilder codeMatchQueryBuilder = QueryBuilders.matchQuery("commonName.chinese", commonName);
            MatchQueryBuilder codeRawMatchQueryBuilder = QueryBuilders.matchQuery("commonName.raw", commonName);
            codeRawMatchQueryBuilder.boost(10f);
            boolQueryBuilder.must(codeMatchQueryBuilder).should(codeRawMatchQueryBuilder);
            // 设置查询条件
            searchSourceBuilder.query(boolQueryBuilder);
            //将 SearchSourceBuilder 添加到 SearchRequest中
            searchRequest.source(searchSourceBuilder);
            //执行查询
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            //取插叙结果
            SearchHits hits = searchResponse.getHits();
            //查询结果列表
            Iterator<SearchHit> iterator = hits.iterator();
            //存放品牌
            LinkedHashSet<Map<String,Object>> goodsBrandCatParam = new LinkedHashSet<>();
            LinkedHashSet<Map<String, Object>> mapList = new LinkedHashSet<>();
            //存放catId
            LinkedHashSet<String> catIds = new LinkedHashSet<>();
            while (iterator.hasNext()) {
                SearchHit searchHit = iterator.next();
                //打印文档对象，以json格式输出
                System.out.println(searchHit.getSourceAsString());
                //取文档的属性
                Map<String, Object> source = searchHit.getSourceAsMap();
                if(null != source.get("brandId") && "" != source.get("brandId")
                        && null != source.get("brandName") && "" != source.get("brandName") ){
                    //保存商品的品牌
                    Map<String,Object> brandmap = new HashMap<>();
                    brandmap.put("brandId",source.get("brandId"));
                    brandmap.put("brandName",source.get("brandName"));
                    goodsBrandCatParam.add(brandmap);
                }
                //存放catIds
                catIds.add((String) source.get("catId"));
            }
            //根据分类id 查询商品分类属性
            if(!catIds.isEmpty()){
                mapList = queryCatAttribute(catIds);
            }
            map.put("gdbGoodsAttParams",mapList);
            map.put("goodsBrandCatParam",goodsBrandCatParam);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static  LinkedHashSet<Map<String,Object>> queryCatAttribute(LinkedHashSet<String> catIds){
        //商品属性查询
        LinkedHashSet<Map<String,Object>> goodsAttributeResults= esGoodsCommonAttributeAssociationMapper.esSelectAttributes(catIds);
        if(null != goodsAttributeResults && goodsAttributeResults.size() > 0) {
            //根据商品属性id查询属性内容
            for (Map<String,Object> goodsAttribute : goodsAttributeResults) {
                LinkedHashSet<Map<String,Object>> goodsAttributeContent =  esGoodsCommonAttributeAssociationMapper.esSelectAttContents((Integer) goodsAttribute.get("id"));
                goodsAttribute.put("goodsAttributeContentResults",goodsAttributeContent);
            }
        }
        return goodsAttributeResults;
    }
}
